const path = require("path")
const fileUtils = require("./../util/file_util")
//创建WebSocketServer
const WebSocket = require("ws")
const wss = new WebSocket.Server({
    port: 9998
})
//对客户端链接是事件监听 
module.exports.listen = () => {
    wss.on("connection", client => {
        console.log("有客户端连接");
        //对客户端连接接受数据监听
        client.on("message", async msg => {
            console.log("客户端发送了数据" + msg);
            let payload = JSON.parse(msg)
            const action = payload.action
            if (action === "getData") { //action === "getData" 发送数据给客户端
                let filePath = "../data/" + payload.chartName + ".json"
                filePath = path.join(__dirname, filePath)
                const result = await fileUtils.getFileJsonData(filePath)
                payload.data = result
                client.send(JSON.stringify(payload))
            } else {
                //将收到的数据转发给其他客户端
                wss.clients.forEach(client => {
                    // client.send(JSON.stringify(JSON.parse(msg)), { binary: false });
                    client.send((msg), { binary: false })//关闭二进制数据
                })
            }
            // client.send("服务端向客户端发送hello socket")
        })
    })
}